package codeRandomThoughts.Test18四数之和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution2 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        //准备工作
        Arrays.sort(nums);
        List<List<Integer>> results = new ArrayList<>();
        int left = 0;
        int right = 0;

        for (int i = 0; i < nums.length; i++) {
            //剪枝
            if (nums[i] > target && nums[i] >= 0)
                break;
            //去重
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            for (int j = i + 1; j < nums.length; j++) {
                //剪枝
                if (nums[j] + nums[i] > target && nums[j] + nums[i] >= 0)
                    break;
                //去重
                if (j > i + 1 && nums[j] == nums[j - 1])
                    continue;

                left = j + 1;
                right = nums.length - 1;

                while (left < right) {
                    long sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        List<Integer> result = new ArrayList<>();
                        result.add(nums[i]);
                        result.add(nums[j]);
                        result.add(nums[left]);
                        result.add(nums[right]);
                        results.add(result);

                        while (left < right && nums[right] == nums[right - 1]) right--;
                        while (left < right && nums[left] == nums[left + 1]) left++;

                        right--;
                        left++;
                    }
                }
            }
        }
        return results;
    }
}
